﻿namespace HySoft.Cash.Business
{
    using Huayou.Common.Database;
    using Huayou.Utils;
    using HySoft.Cash.BaseClass;
    using HySoft.Cash.DB;
    using HySoft.Cash.Structure;
    using System;
    using System.Data;
    using System.Web.UI;
    using System.Data.SqlClient;
    using System.Configuration;
    using System.Collections.Generic;

    public class TinvoicelistBN : BaseBusiness
    {
        /// <summary>
        /// 根据客户借的 本金计算利息
        /// </summary>
        /// <param name="principle"></param>
        /// <returns></returns>
        public static decimal CalcInterest(decimal principle)
        {
            int invoiceDueDays = 0;
            decimal dailyRate = 0M;
            return CalcInterest(principle, dailyRate, invoiceDueDays);
        }

        public static void UpdateOtherFee(int orgID, int invoiceID, Guid invoiceGuid, decimal newPenalty, decimal oldPenalty, decimal newLateInterestCharges, decimal oldLateInterestCharges)
        {
            int adminID = 1;//管理员ID暂定为1
            Guid capitalFlowingID = Guid.NewGuid();
            decimal diffPenalty = 0 - (newPenalty - oldPenalty);
            decimal diffLateInterestCharges = 0 - (newLateInterestCharges - oldLateInterestCharges);
            decimal diffFeeBalance = 0 - (diffPenalty + diffLateInterestCharges);

            string sqlTempClosingBalance = string.Format("([dbo].[UF_GetCreditBalance]({0}))", orgID);
            string sqlTempCurrentBalance = string.Format("([dbo].[UF_GetFeeBalance]({0}))+ {1}", orgID, (0 - (diffPenalty + diffLateInterestCharges)));

            string sqlCapitalFlowing = string.Format("INSERT INTO [tCapitalFlowing] ([ID],[OrgID],[Direction],[Principal],[Interest],[Penalty],[LateInterestCharges],[Total],[Memo],[TransDate],[TransOperater],[Other1],[Other2],[Other3],[Other4],[LastCreditBalance],[LastFeeBalance]) VALUES ('{0}' ,{1} ,{2} ,{3} ,{4} ,{5} ,{6} ,{7} ,'{8}' ,'{9}' ,{10} ,0 ,0 ,'' ,'',{11},{12})",
                capitalFlowingID, orgID, (int)CapitalFlowingDirections.Other, 0, 0, diffPenalty, diffLateInterestCharges, diffPenalty + diffLateInterestCharges, "Change Other Fee for Invoice " + invoiceGuid.ToString(), SafeDateTime.LocalNow, adminID, sqlTempClosingBalance, sqlTempCurrentBalance);
            string sqlCapitalRelateMemo = string.Format("Invoice {0}({1}) change penalty from {2} to {3}; change LateInterestCharges from {4} to {5}", invoiceID, invoiceGuid, oldPenalty, newPenalty, oldLateInterestCharges, newLateInterestCharges);
            string sqlCapitalRelate = string.Format("INSERT INTO [tCapitalFlowingRelating] ([Direction] ,[CapitalFlowingID] ,[RalatingID] ,[Memo]) VALUES ({0} ,'{1}' ,'{2}' ,'{3}')",
                (int)CapitalFlowingDirections.Other, capitalFlowingID, invoiceGuid, "Invoice other fee");

            //string sqlCredit = string.Format("UPDATE [tOrgInfo]   SET [CurrentBalance] = [CurrentBalance]+{1},[AvailableBalance] = [CreditLimit]-[CurrentBalance]-{1} WHERE Sid={0}", orgID, 0 - (diffPenalty + diffLateInterestCharges));
            string sqlCredit = string.Format("UPDATE [tOrgInfo]   SET [FeeBalance] = [FeeBalance]+{1} WHERE Sid={0}", orgID, diffFeeBalance);

            SqlParameter[] commandParameters = new SqlParameter[] { new SqlParameter("@Sid", invoiceID),new SqlParameter("@orgSid",orgID), new SqlParameter("@dPenalty", newPenalty), new SqlParameter("@dInterestCharges", newLateInterestCharges) ,new SqlParameter("@diffFeeBalance",diffFeeBalance)};
            using (SqlConnection conn = new SqlConnection(ConfigurationManager.AppSettings["SQLConnString"]))
            {
                conn.Open();
                SqlTransaction tran = conn.BeginTransaction();

                try
                {
                    //1.修改Invoice信息
                    SqlHelper.ExecuteNonQuery(tran, CommandType.StoredProcedure, "UptInvoiceOtherFee", commandParameters);

                    //2.更新资金流动表
                    SqlHelper.ExecuteNonQuery(tran, CommandType.Text, sqlCapitalFlowing);
                    SqlHelper.ExecuteNonQuery(tran, CommandType.Text, sqlCapitalRelate);

                    //3.更新用户信用
                    SqlHelper.ExecuteNonQuery(tran, CommandType.Text, sqlCredit);

                    tran.Commit();
                }
                catch
                {
                    tran.Rollback();
                }
            }
        }

        public static decimal CalcInterest(decimal principle, decimal dailyRate, int invoiceDueDays)
        {
            if (dailyRate == 0M)
            {
                dailyRate = Convert.ToDecimal(Config.GetSetting("DailyInterestRate"));
            }

            if (invoiceDueDays == 0)
            {
                invoiceDueDays = Convert.ToInt32(Config.GetSetting("InvoiceOverDueDays"));
            }
            return principle * 0.01M * dailyRate * invoiceDueDays;
        }

        public static string GetInvoiceStatusText(InvoiceStatuses invoiceStatus)
        {
            string statusText = string.Empty;
            InvoiceStatuses status = invoiceStatus;
            switch (status)
            {
                case InvoiceStatuses.InitStatus:
                    statusText = "New";
                    break;
                case InvoiceStatuses.Deleted:
                    statusText = "Deleted";
                    break;
                //case InvoiceStatuses.Sent:
                //    statusText = "Sent";
                //    break;
                case InvoiceStatuses.Overdue:
                    statusText = "Overdue";
                    break;
                case InvoiceStatuses.Closed:
                    statusText = "Closed";
                    break;
                default:
                    break;
            }
            return statusText;
        }

        private TinvoicelistDB db;

        public TinvoicelistBN(Page page)
            : base(page)
        {
            this.db = null;
            this.db = new TinvoicelistDB(base.curDBOperater);
        }

        public TinvoicelistBN(Page page, DBOperate oper)
            : base(page, oper)
        {
            this.db = null;
            this.db = new TinvoicelistDB(base.curDBOperater);
        }

        public bool Add(TinvoicelistDT detail)
        {
            bool flag = false;
            try
            {
                try
                {
                    flag = this.db.Add(detail);
                }
                catch (Exception exception)
                {
                    throw exception;
                }
            }
            finally
            {
            }
            return flag;
        }

        public bool Delete(int Sid)
        {
            bool flag = false;
            try
            {
                try
                {
                    flag = this.db.Delete(Sid);
                }
                catch (Exception exception)
                {
                    throw exception;
                }
            }
            finally
            {
            }
            return flag;
        }

        public void Dispose()
        {
            base.Dispose();
            if (this.db != null)
            {
                this.db = null;
            }
        }

        public bool Edit(TinvoicelistDT detail)
        {
            bool flag = false;
            try
            {
                try
                {
                    flag = this.db.Edit(detail);
                }
                catch (Exception exception)
                {
                    throw exception;
                }
            }
            finally
            {
            }
            return flag;
        }

        public TinvoicelistDT Get(int Sid)
        {
            TinvoicelistDT tdt = null;
            try
            {
                try
                {
                    tdt = this.db.Get(Sid);
                }
                catch (Exception exception)
                {
                    throw exception;
                }
            }
            finally
            {
            }
            return tdt;
        }

        /// <summary>
        /// 获取逾期未付的账单数量
        /// </summary>
        /// <param name="orgID"></param>
        /// <returns></returns>
        public static int GetOverDueInvoiceCount(int orgID)
        {
            //int overDueDays = AppSettings.InvoiceOverDueDays;
            //overDueDays = 0 - overDueDays;
            //DateTime overDueDate = SafeDateTime.LocalNow.AddDays(overDueDays);
            string commondText = string.Format("select count(*) from tInvoiceList where OrgSid={0} and IsValid={1}", orgID, (int)InvoiceStatuses.Overdue);
            return Convert.ToInt32(SqlHelper.ExecuteScalar(AppSettings.ConnectionString, CommandType.Text, commondText));
        }

        /// <summary>
        /// 获取逾期未付的账单列表
        /// </summary>
        /// <returns></returns>
        public static List<TinvoicelistDT> GetOverDueInvoiceList()
        {
            return GetOverDueInvoiceList(0);
        }

        /// <summary>
        /// 获取逾期未付的账单列表
        /// </summary>
        /// <param name="orgID"></param>
        /// <returns></returns>
        public static List<TinvoicelistDT> GetOverDueInvoiceList(int orgID)
        {
            List<TinvoicelistDT> list = new List<TinvoicelistDT>();
            string commondText = string.Empty;
            if (orgID <= 0)
            {
                commondText = string.Format("select * from tInvoiceList where IsValid={0}", (int)InvoiceStatuses.Overdue);
            }
            else
            {
                commondText = string.Format("select * from tInvoiceList where OrgSid={0} and IsValid={1}", orgID, (int)InvoiceStatuses.Overdue);
            }

            using (SqlDataReader reader = SqlHelper.ExecuteReader(AppSettings.ConnectionString, CommandType.Text, commondText))
            {
                while (reader.Read())
                {
                    TinvoicelistDT currentInvoice = TinvoicelistDT.ConvertFrom(reader);
                    list.Add(currentInvoice);
                }
            }

            return list;
        }


        public DataTable GetList()
        {
            base.DBFieldList = "Sid,OrgSid,InvoiceDate,IsValid,Note,Principal,Interest,Penalty,LateInterestCharges,PrincipalPaid, InterestPaid , PenaltyPaid , LateInterestChargesPaid,RemainBalancePaid,(Penalty + LateInterestCharges) as OtherFee,PaymentDate,Guid,PreviousBalance,PaidFromPreviousBalance,PreviousInvoiceID";
            base.DBTable = "tInvoiceList";
            return base.CommonGetList();
        }

        public void QueryGuid(string Guid)
        {
            if ((Guid != null) && (Guid.Trim() != ""))
            {
                base.Filter = "Guid like '%" + StringUtils.ToSQL(Guid) + "%'";
            }
        }

        public void QueryLateInterestCharges(string InterestCharges)
        {
            if ((InterestCharges != null) && (InterestCharges.Trim() != ""))
            {
                base.Filter = "LateInterestCharges like '%" + StringUtils.ToSQL(InterestCharges) + "%'";
            }
        }

        //public void QueryInvoiceAmount(string InvoiceAmount)
        //{
        //    if ((InvoiceAmount != null) && (InvoiceAmount.Trim() != ""))
        //    {
        //        base.Filter = "InvoiceAmount like '%" + StringUtils.ToSQL(InvoiceAmount) + "%'";
        //    }
        //}

        public void QueryInvoiceDate(DateTime InvoiceDate)
        {
            if ((InvoiceDate != null))
            {
                base.Filter = "InvoiceDate = '" + InvoiceDate + "'";
            }
        }

        public void QueryInvoiceDateBegin(DateTime invoiceDate)
        {
            if (invoiceDate != null)
            {
                base.Filter = string.Format("InvoiceDate >= '{0}' ", invoiceDate);
            }
        }

        public void QueryInvoiceDateEnd(DateTime invoiceDate)
        {
            if (invoiceDate != null)
            {
                base.Filter = string.Format("InvoiceDate <= '{0}' ", invoiceDate);
            }
        }

        public void QueryIsValid(InvoiceStatuses IsValid)
        {
            base.Filter = "IsValid= " + (int)IsValid;
        }

        public void QueryIsValidNot(InvoiceStatuses isValid)
        {
            base.Filter = "IsValid != " + (int)isValid;
        }

        public void QueryNote(string Note)
        {
            if ((Note != null) && (Note.Trim() != ""))
            {
                base.Filter = "Note like '%" + StringUtils.ToSQL(Note) + "%'";
            }
        }

        public void QueryOrgSid(int OrgSid)
        {
            base.Filter = "OrgSid= " + OrgSid;
        }

        public void QueryPaymentDate(string PaymentDate)
        {
            if ((PaymentDate != null) && (PaymentDate.Trim() != ""))
            {
                base.Filter = "PaymentDate like '%" + StringUtils.ToSQL(PaymentDate) + "%'";
            }
        }

        public void QueryPenalty(string Penalty)
        {
            if ((Penalty != null) && (Penalty.Trim() != ""))
            {
                base.Filter = "Penalty like '%" + StringUtils.ToSQL(Penalty) + "%'";
            }
        }

        //public void QueryReceiveAmount(string ReceiveAmount)
        //{
        //    if ((ReceiveAmount != null) && (ReceiveAmount.Trim() != ""))
        //    {
        //        base.Filter = "ReceiveAmount like '%" + StringUtils.ToSQL(ReceiveAmount) + "%'";
        //    }
        //}

        public void QuerySid(int Sid)
        {
            base.Filter = "Sid= " + Sid;
        }
    }
}

